package com.polaris.live.ui.main.activity

import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.TimeUtils
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.ktx.messaging
import com.polaris.live.App
import com.polaris.live.R
import com.polaris.live.cache.CommonCache
import com.polaris.live.common.AppModule
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.cacha.DisplayUtil
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.ServerConfig
import com.polaris.live.common.event.EventMessage
import com.polaris.live.common.event.EventStringMessage
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.network.request
import com.polaris.live.common.resp.AppVersionVo
import com.polaris.live.common.util.DateUtils
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.constant.LiveConst
import com.polaris.live.databinding.ActivityMainBinding
import com.polaris.live.dialog.GlobalDialogManager
import com.polaris.live.dialog.TogetherReceive2Dialog
import com.polaris.live.im.manager.ImManager
import com.polaris.live.im.manager.ImSessionManager
import com.polaris.live.manager.AppConfigManager
import com.polaris.live.manager.LiveStateManager
import com.polaris.live.manager.PageManager
import com.polaris.live.net.liveService
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.event.AppVersionUpdateEvent
import com.polaris.live.resp.event.FcmRouterEvent
import com.polaris.live.resp.event.GameDotUpdateEvent
import com.polaris.live.resp.event.MainRouterEvent
import com.polaris.live.resp.event.NewLivingTimeEvent
import com.polaris.live.resp.event.RechargeTodayEvent
import com.polaris.live.resp.event.StartPartyRouterEvent
import com.polaris.live.translation.R.string
import com.polaris.live.ui.game.GameUtils
import com.polaris.live.ui.main.fragment.HotFragment
import com.polaris.live.ui.main.fragment.MeFragment
import com.polaris.live.ui.main.game.HomeCenterGameFragment
import com.polaris.live.ui.main.live.LiveFragment
import com.polaris.live.ui.message.fragment.HomeMainMessageFragment
import com.polaris.live.utils.CommonUtils.toBoolean
import com.polaris.live.utils.StartLiveProxy
import com.polaris.live.utils.fragment.FragmentChangeManager
import com.polaris.live.utils.interfaces.OnAutoRefreshListener
import com.polaris.live.utils.interfaces.OnGotoListener
import com.polaris.live.utils.interfaces.OnGotoListener.GotoData
import com.polaris.live.utils.interfaces.OnRefreshStateListener
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.utils.sensor.impl.ToolsModuleHelper
import com.polaris.live.utils.zego.LiveEngineManage
import com.polaris.live.viewmodel.MainViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 主页
 *
 * @author Created by 半仙 on 2023/7/31/031 17:10
 */
class MainActivity : BaseVbActivity<MainViewModel, ActivityMainBinding>() {

    /**
     * 当前显示的 tab内容 index
     */
    private var mCurTabIndex = 0

    private val mTitles: MutableList<String> = mutableListOf()

    private var mResImages: Array<IntArray> = emptyArray()

    private lateinit var mFragmentChangeManager: FragmentChangeManager

    private var mIsShowUpdate = false

    private var mVersion: AppVersionVo? = null

    private var mIsNeedClear = false

    //状态监听
    private val mNetStateListener = object : NetworkUtils.OnNetworkStatusChangedListener {
        override fun onDisconnected() {
        }

        override fun onConnected(networkType: NetworkUtils.NetworkType?) {
            if (networkType == NetworkUtils.NetworkType.NETWORK_WIFI) {
                mViewModel.downloadPag()
            }
        }
    }

    override fun initImmersionBar() {}

    override fun initView(savedInstanceState: Bundle?) {
        PageManager.openMain()

        EventBus.getDefault().register(this)

        NetworkUtils.registerNetworkStatusChangedListener(mNetStateListener)

        //设置一个底部的高度
        updateBottomHeight()

        val data = DisplayUtil.getDisplayPage()
        data.forEach {
            when (it.primaryPage) {
                DisplayUtil.LIVE -> {
                    mResImages += intArrayOf(R.drawable.tab_home, R.drawable.tab_home2)
                    mTitles.add(StringUtils.getString(string.friend_ship))
                }

                DisplayUtil.COMMUNITY -> {
                    mResImages += intArrayOf(R.drawable.tab_community, R.drawable.tab_community2)
                    mTitles.add(StringUtils.getString(string.community))
                }

                DisplayUtil.GAME -> {
                    mResImages += intArrayOf(R.drawable.tab_game, R.drawable.tab_game2)
                    mTitles.add(StringUtils.getString(string.diamond_game))
                }

                DisplayUtil.MESSAGE -> {
                    mResImages += intArrayOf(R.drawable.tab_message, R.drawable.tab_message2)
                    mTitles.add(StringUtils.getString(string.message))
                }

                DisplayUtil.MINE -> {
                    mResImages += intArrayOf(R.drawable.tab_user, R.drawable.tab_user2)
                    mTitles.add(StringUtils.getString(string.my_string))
                }
            }
        }

        initFragment()

        mBinding.mainTabLayout.setTabData(mResImages, mTitles.toTypedArray(), mCurTabIndex)
        mBinding.mainTabLayout.setOnClickCallBack { _, index ->
            switchTab(index)
        }
        mBinding.mainTabLayout.setRefreshMainBack {
            mFragmentChangeManager.clearFragment()
        }
        initListener()
        initObserver()
        //初始化im
        initIm()
        //初始化直播相关的东西
        initLive()
        initData()
        mViewModel.checkTaskRedShow()

        if (ServerConfig.isDebug() || !ServerConfig.isProdServer()) {
            ToolsModuleHelper.attach(this)
        }

        lifecycleScope.launch {
            delay(1000)

            if (!mIsShowUpdate) {
                mViewModel.updateVersion()
            }
        }
        GlobalPopupManager.showCompletePopup(this, {}, {})
        UserManager.changeRechargeAcState(true)
    }

    fun clearFragment() {
        mIsNeedClear = true
    }
    //=====================================================初始化IM================================================================================

    private fun initIm() {
        ImManager.startImService()

        //获取计算所有的未读数
        ImSessionManager.triggerSessionUnreadCountCalculation()
    }

    private fun initLive() {
        AppConfigManager.getConfig(CommonConst.Zego.zegoAppId)?.let { appId ->
            LiveEngineManage.createEngine(appId.toLong())
        }
    }

    private fun initListener() {
        ImSessionManager.observeUnreadCount(this) { totalUnreadCount, _, _, _ ->
            mBinding.mainTabLayout.setNumber(totalUnreadCount)
        }
    }

    private fun initData() {
        EventBus.getDefault().post(EventStringMessage(BizEventConst.LOGIN_FINISH, ""))

        mViewModel.getGifts()
        mViewModel.downloadPag()
        mViewModel.quickLogin()
        mViewModel.consumableReceive()
        if (UserManager.getUser().sex != AppConst.UserSex.NONE) {
            mViewModel.getLiveResource()
        }
        GameUtils.getFirstGameList()

        App.onInitState {
            LiveStateManager.changeState(LiveConst.State.NONE)

            //如果还在通话
            if (UserManager.getUser().call?.calling == AppConst.YES) {
                mViewModel.callEndState()
            }
            mViewModel.viewModelScope.launch {
                LiveEngineManage.withLogin(this@MainActivity, {
                    if (UserManager.getUser().live?.living == AppConst.YES) {
                        GlobalDialogManager.showCommonDialog(
                            this@MainActivity,
                            getString(string.shutdown_exception),
                            onConfirmListener = {
                                val liveType = UserManager.getUser().live?.liveType
                                if (it) {
                                    StartLiveProxy.builder(this@MainActivity)
                                        .recoverLive(mViewModel,liveType)
                                } else {
                                    val live = UserManager.getUser().live
                                    when (liveType) {
                                        LiveConst.Type.PARTY_GAME_LIVE -> {
                                            endGameSiteState()
                                            if (live?.partyGaming == AppConst.YES) {
                                                mViewModel.partyGameEnd()
                                            }
                                        }

                                        else -> {
                                            mViewModel.liveEndState()
                                        }
                                    }
                                }
                            })
                    } else {
                        val gaming = UserManager.getUser().live?.partyGaming
                        if (gaming == AppConst.YES) {
                            mViewModel.partyGameGaming()
                        } else {
                            endGameSiteState()
                        }
                    }
                })
            }
        }

        mViewModel.clearPhotos(cacheDir)

        //订阅一个全局的主题
        Firebase.messaging.subscribeToTopic(CommonConst.FirebaseTopic.ALL)

        //福袋订阅
        if (UserManager.getUser().setting?.luckyBagNotice == AppConst.YES) {
            Firebase.messaging.subscribeToTopic(CommonConst.FirebaseTopic.LUCKY_BAG)
        } else {
            Firebase.messaging.unsubscribeFromTopic(CommonConst.FirebaseTopic.LUCKY_BAG)
        }
    }

    private fun initObserver() {
        mViewModel.mUpdateLiveData.observe(this) {
            val forceVersion = it.version
            if (forceVersion != null) {
                if (!forceVersion.promptOnlyOnce) {
                    CacheUtil.setMainUpdateVersion(forceVersion.buildVersion.toString(), false)
                }
                if (forceVersion.buildVersion > AppModule.getAppVersion()) {
                    mVersion?.let { version ->
                        if (forceVersion.forceUpdate) {
                            GlobalDialogManager.showUpgradeDialog(
                                this,
                                mainVersionVo = forceVersion
                            )
                        } else if (version.buildVersion > forceVersion.buildVersion) {
                            val date =
                                CacheUtil.getUpdateVersionTime(version.buildVersion.toString())
                            if (date == 0L || !DateUtils.isOneDay(
                                    date,
                                    System.currentTimeMillis()
                                )
                            ) {
                                CacheUtil.setUpdateVersionTime(version.buildVersion.toString())
                                GlobalDialogManager.showUpgradeDialog(this, version)
                            }
                        } else if (!CacheUtil.getMainUpdateVersion(forceVersion.buildVersion.toString())) {
                            val date =
                                CacheUtil.getMainUpdateVersionTime(forceVersion.buildVersion.toString())
                            if (date == 0L || !DateUtils.isOneDay(
                                    date,
                                    System.currentTimeMillis()
                                )
                            ) {
                                CacheUtil.setMainUpdateVersionTime(forceVersion.buildVersion.toString())
                                GlobalDialogManager.showUpgradeDialog(
                                    this,
                                    mainVersionVo = forceVersion
                                )
                            }
                        }
                    } ?: run {
                        if (forceVersion.forceUpdate) {
                            GlobalDialogManager.showUpgradeDialog(
                                this,
                                mainVersionVo = forceVersion
                            )
                        } else if (!CacheUtil.getMainUpdateVersion(forceVersion.buildVersion.toString())) {
                            val date =
                                CacheUtil.getMainUpdateVersionTime(forceVersion.buildVersion.toString())
                            if (date == 0L || !DateUtils.isOneDay(
                                    date,
                                    System.currentTimeMillis()
                                )
                            ) {
                                CacheUtil.setMainUpdateVersionTime(forceVersion.buildVersion.toString())
                                GlobalDialogManager.showUpgradeDialog(
                                    this,
                                    mainVersionVo = forceVersion
                                )
                            }
                        }
                    }
                }
            }
        }
        mViewModel.mLiveResourceLiveData.observe(this) { resultState ->
            parseState(resultState, {
                val times = CommonCache.getNewLivingTime()
                val today = TimeUtils.isToday(times)
                if (it.reminderLive.toBoolean()) {
                    if (!today) {
                        CommonCache.setNewLivingCount(0)
                    }
                    if (CommonCache.getNewLivingCount() < MainViewModel.MAX_SHOW_DIALG || !today) {
                        GlobalDialogManager.showNewLiving(this)
                    }
                }

                CommonCache.setLiveResource(it)
            })
        }
        mViewModel.mPartyGameLiveData.observe(this) { resulState ->
            parseState(resulState, { resp ->
                if (resp.anchorId != null) {
                    resp.content?.let { it1 ->
                        GlobalDialogManager.showCommonDialog(
                            this@MainActivity, it1,
                            onConfirmListener = {
                                if (it) {
                                    Router.instance.setPath(RoutePath.PARTY_GAME_SPECTATOR_ACTIVITY)
                                        .withLong(LiveConst.Params.ANCHORID, resp.anchorId)
                                        .navigation(this)
                                } else {
                                    endGameSiteState()
                                    mViewModel.partyGameEnd()
                                }
                            })
                    }
                } else {
                    endGameSiteState()
                    mViewModel.partyGameEnd()
                }
            })
        }
        /**
         *聚合每日领取奖励
         */
        mViewModel.mConsumableReceiveLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.isNotEmpty()) {
                    TogetherReceive2Dialog.show(this, it)
                }
            })
        }
    }

    private fun endGameSiteState() {
        val live = UserManager.getUser().live
        if (live?.partySite != -1) {
            mViewModel.partyGameSiteEnd()
        }
    }

    /**
     * 游戏红点更新
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGameDotUpdateEvent(event: GameDotUpdateEvent) {
        mBinding.mainTabLayout.setGameCountRed(event.count)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)

        val tabIndex = intent?.getStringExtra("tabIndex")?.toIntOrNull()
        val listIndex = intent?.getStringExtra("listIndex")?.toIntOrNull()

        gotoMain(tabIndex, listIndex)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: EventMessage) {
        when (event.from) {
            BizEventConst.INFO_UPDATA -> {//完善资料后通知 主页面更新用户数据
                mViewModel.getUser()
                mViewModel.consumableReceive()
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun onVersionUpdateEvent(event: AppVersionUpdateEvent) {
        EventBus.getDefault().removeStickyEvent(event)
        if (event.version.forceUpdate) {
            GlobalDialogManager.showUpgradeDialog(this, event.version)
            mIsShowUpdate = true
        } else {
            mVersion = event.version
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun onRouterEvent(event: FcmRouterEvent) {
        EventBus.getDefault().removeStickyEvent(event)

        if (event.router != null) {
            RouterUtils.routerGoto(event.router)
        }
        if (event.router2 != null) {
            RouterUtils.routerGoto(event.router2)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNewLivingTimeEvent(event: NewLivingTimeEvent) {
        if (event.isStartLive) {
            StartLiveProxy.builder(this)
                .startNotCheckPhotosLive(mViewModel, LiveConst.Type.LIVE_AND_MATCH)
        } else {
            mViewModel.timingLivingDialog(this)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMainRouterEvent(event: MainRouterEvent) {
        if (this::mFragmentChangeManager.isInitialized) {
            gotoMain(event.tabIndex, event.listIndex)
        } else {
            //这里暂时只做一层
            mBinding.mainTabLayout.initCurrentItem(event.tabIndex)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onStartPartyRouterEvent(event: StartPartyRouterEvent) {
        ActivityUtils.finishOtherActivities(MainActivity::class.java)
        if (event.boolean) {
            mViewModel.request({ liveService.getPartyRoom() }, {
                if (it.roomId?.isNotEmpty() == true) {
                    val liveType = UserManager.getUser().live?.liveType
                    StartLiveProxy.builder(this)
                        .recoverLive(mViewModel, liveType, it.roomId)
                } else {
                    //开启派对
                    Router.builder(RoutePath.SET_PARTY_COVER_ACTIVITY)
                        .navigation(this)
                }
            })

        }
    }

    //充值页返回后弹出充值弹窗
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onShowTodayRechargeEvent(event: RechargeTodayEvent) {
        val index = DisplayUtil.getPrimaryIdByCurrentIndex(getCurrentIndex())
        val topActivity = ViewUtils.getAliveTopActivity() ?: return
        if (index == DisplayUtil.MINE && topActivity is MainActivity) {
            GlobalPopupManager.showTodayRecharge(mViewModel)
        }
    }

    private fun gotoMain(tabIndex: Int?, listIndex: Int?) {
        if (tabIndex != null) {
            val data = if (listIndex != null) {
                GotoData(listIndex)
            } else {
                null
            }
            switchTab(tabIndex, data)
        }
    }

    override fun onResume() {
        super.onResume()
        if (mIsNeedClear) {
            mIsNeedClear = false
            mFragmentChangeManager.clearFragment()
            switchFragment()
        }

        val liveFragment = mFragmentChangeManager.getCurrentFragment(DisplayUtil.LIVE)
        if (liveFragment is OnRefreshStateListener) {
            liveFragment.onRefreshState()
        }
    }

    //=======================================================底部tablayout设置=====================================================================
    private fun initFragment() {
        val (primaryPage, secondaryPage) = DisplayUtil.getAppSecondaryPageVo()

        mCurTabIndex = DisplayUtil.getCurrentIndexByPrimaryId(primaryPage)
        val realTabIndex = DisplayUtil.getPrimaryIdByCurrentIndex(mCurTabIndex)

        mBinding.mainTabLayout.initCurrentItem(mCurTabIndex)

        //消息界面必须先初始化
        val initFragments =
            (listOf(DisplayUtil.MESSAGE, DisplayUtil.GAME) + realTabIndex).distinct()
        mFragmentChangeManager = FragmentChangeManager(
            supportFragmentManager,
            R.id.main_child_fragment,
            initFragments,
            realTabIndex
        ) {
            when (it) {
                DisplayUtil.LIVE -> LiveFragment().apply {
                    if (primaryPage == DisplayUtil.LIVE) {
                        onGoto(
                            GotoData(
                                DisplayUtil.getCurrentIndexBySecondaryPrimaryId(
                                    DisplayUtil.LIVE,
                                    secondaryPage
                                )
                            )
                        )
                    }
                }

                DisplayUtil.COMMUNITY -> HotFragment().apply {
                    if (primaryPage == DisplayUtil.COMMUNITY) {
                        onGoto(
                            GotoData(
                                DisplayUtil.getCurrentIndexBySecondaryPrimaryId(
                                    DisplayUtil.COMMUNITY,
                                    secondaryPage
                                )
                            )
                        )
                    }
                }

                DisplayUtil.GAME -> HomeCenterGameFragment()
                DisplayUtil.MESSAGE -> HomeMainMessageFragment()
                DisplayUtil.MINE -> MeFragment().apply {
                    setOnShowCustomerRead { red ->
                        this@MainActivity.mBinding.mainTabLayout.setMeRed(red)
                    }
                }

                else -> null
            }
        }
    }

    private fun switchFragment() {
        mFragmentChangeManager.switchFragment(DisplayUtil.getPrimaryIdByCurrentIndex(mCurTabIndex))
    }

    private fun switchTab(tabIndex: Int, gotoData: GotoData? = null) {
        mBinding.mainTabLayout.setCurrentItem(tabIndex)
        if (mCurTabIndex == tabIndex) {
            autoRefresh(tabIndex)
            return
        }
        mCurTabIndex = tabIndex
        switchFragment()

        val fragment = mFragmentChangeManager.getCurrentFragment(
            DisplayUtil.getPrimaryIdByCurrentIndex(mCurTabIndex)
        )
        if (fragment is OnGotoListener && gotoData != null) {
            fragment.onGoto(gotoData)
        }
    }

    private fun autoRefresh(tabIndex: Int) {
        val fragment = mFragmentChangeManager.getCurrentFragment(
            DisplayUtil.getPrimaryIdByCurrentIndex(tabIndex)
        )
        if (fragment is OnAutoRefreshListener) {
            fragment.onAutoRefresh()
        }
    }

    private fun updateBottomHeight() {
        ViewUtils.setMargin(
            mBinding.mainTabLayout,
            bottomMargin = NavigationBarUtils.getNavigationBarHeight(this)
        )

        mBinding.mainTabLayout.post {
            ViewUtils.setMargin(
                mBinding.mainChildFragment,
                bottomMargin = NavigationBarUtils.getNavigationBarHeight(this) + mBinding.mainTabLayout.height
            )
        }
    }

    fun getCurrentIndex(): Int {
        return mCurTabIndex
    }

    override fun onBackPressed() {
        moveTaskToBack(false)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        NetworkUtils.unregisterNetworkStatusChangedListener(mNetStateListener)

        PageManager.closeMain()
    }
}